package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result seckillVoucher(Long voucherId) {
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        LocalDateTime beginTime = seckillVoucher.getBeginTime();
        LocalDateTime endTime = seckillVoucher.getEndTime();
        LocalDateTime now = LocalDateTime.now();
        if(beginTime.isAfter(now)) {
            return Result.fail("商品秒杀尚未开始");
        }

        if(endTime.isBefore(now)) {
            return Result.fail("秒杀已经结束");
        }
        if( seckillVoucher.getStock() < 1) {
            return Result.fail("秒杀券库存不足");
        }
        return createVoucherOrder(voucherId);
    }
    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:" + userId,
                stringRedisTemplate);
        boolean tryLock = simpleRedisLock.tryLock(10L);
        if(!tryLock) {
            return Result.fail("不允许重复下单");
        }
        try {
            // 查询订单
            int count = query().eq("user_id", userId)
                    .eq("voucher_id", voucherId).count();
            if (count > 0) {
                return Result.fail("您已经抢过该优惠券");
            }
            boolean success = seckillVoucherService.update().setSql("stock=stock-1")
                    .eq("voucher_id", voucherId).ge("stock", 0).update();
            if (!success) {
                return Result.fail("商品库存不足");
            }

            VoucherOrder voucherOrder = new VoucherOrder();
            voucherOrder.setVoucherId(voucherId);

            voucherOrder.setUserId(userId);
            Long orderId = redisIdWorker.nextId("order");
            voucherOrder.setId(orderId);
            save(voucherOrder);
            return Result.ok(orderId);
        }finally {
            simpleRedisLock.unlock();
        }
    }

    //普通锁实现
    @Transactional
    public Result createVoucherOrder1(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        synchronized (userId.toString().intern()) {
            Integer count = query().eq("user_id", userId)
                    .eq("voucher_id", voucherId).count();
            if(count > 0) {
                return Result.fail("您已经抢过该优惠券");
            }
            boolean success = seckillVoucherService.update().setSql("stock=stock-1")
                    .eq("voucher_id", voucherId).ge("stock",0).update();
            if(!success) {
                return Result.fail("商品库存不足");
            }

            VoucherOrder voucherOrder = new VoucherOrder();
            voucherOrder.setVoucherId(voucherId);

            voucherOrder.setUserId(userId);
            Long orderId = redisIdWorker.nextId("order");
            voucherOrder.setId(orderId);
            save(voucherOrder);
            return Result.ok(orderId);
        }

    }
}
